// pages/home/index.js

import {
    getCellphone,
    getLoginStatus
} from '../../api/index'

Page({

    data: {
        from: "",
        msg: "初始化数据声明",
        avatarUrl: "",
        username: "",
        password: "",
        isLogin: ""
    },

    onLoad(options) {
        const fromPage = options.from
        this.setData({ from: fromPage })
        const { username, password } = this.data
        this.setData({ username, password })
        this.getLoginFlag()
    },

    getLoginFlag() {
        const {  username, password } = this.data
        username && password && this.setData({ isDisabled: false })
    },
    async getToHomeIndex() {
        const { from, username, password } = this.data
        if (!username || !password) {
            wx.showToast({
                title: '请输入用户名和密码',
                icon: 'none',
                duration: 1000
            })
        } else {
            const {code, message, token, cookie,profile, account } = await getCellphone({ phone: username, password})
            if (code !== 200 ) {
                wx.showToast({
                    title: message,
                    icon: 'none',
                    duration: 1000
                })
            } else {
                const userInfo = { username: account.userName, ...profile }
                this.setData({ isLogin: token})
                wx.setStorageSync('userInfo', JSON.stringify(userInfo));
                wx.setStorageSync('token', token);
                wx.setStorageSync('cookie', cookie)
                wx.showLoading({
                    title: '登录中',
                    mask: true,
                    duration: 2000
                })
                const url = from ? `/pages/${from}/mine` : '/pages/home/index'
                wx.switchTab({url})
                this.setData({username: "", password: "", from: ''})
            }
        }
    },
    getUserNameAction(e) {
        this.setData({ username: e.detail.value })
        this.getLoginFlag()
    },
    getPasswordAction(e) {
        this.setData({ password: e.detail.value })
        this.getLoginFlag()
    },
    goHome() {
        wx.switchTab({url: '/pages/home/index'})
    },
})